package modelo;

import java.io.Serializable;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author HECTOR
 * 
 */
public class Transporter implements Serializable {
	private String smtpServer;
	private String user;
	private String password;
	private String port;
	private EMail correo;
	private boolean ssl;
	private boolean autentication;

	public Transporter(String smptServer, String user, String password,
			String port, boolean ssl, boolean autentication, String[] to,
			String subject, String message) {
		super();
		this.smtpServer = smptServer;
		this.user = user;
		this.password = password;
		this.port = port;
		this.ssl = ssl;
		this.autentication = autentication;
		this.correo = new EMail(to, subject, message);
	}

	public boolean getSsl() {
		return ssl;
	}

	public boolean getAutentication() {
		return autentication;
	}

	public String getPort() {
		return port;
	}

	public EMail getCorreo() {
		return correo;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSmptServer() {
		return smtpServer;
	}

	public void setSmptServer(String smptServer) {
		this.smtpServer = smptServer;
	}

	public String send() {
		Properties props = new Properties();

		props.put("mail.debug", "true");
		props.put("mail.smtp.auth", this.autentication);
		props.put("mail.smtp.starttls.enable", this.ssl);
		props.put("mail.smtp.host", smtpServer);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.localhost", "comunicacionefectiva.net");
		props.put("mail.smtp.from", "admin@comunicacionefectiva.net");

		Session session = Session.getInstance(props, null);

		try {
			MimeMessage message = new MimeMessage(session);
			for (String recipient : this.getCorreo().getTo()) {
				message.addRecipient(Message.RecipientType.TO,
						new InternetAddress(recipient));
			}
			message.setSubject(this.getCorreo().getSubject());
			message.setSentDate(new Date());
			message.setText(this.getCorreo().getMessage());
			Transport tr = session.getTransport("smtp");
			
			tr.connect(smtpServer, user, password);
			message.saveChanges();
			// tr.send(message, message.getAllRecipients());
			tr.sendMessage(message, message.getAllRecipients());
			tr.close();
			return null;
		} catch (MessagingException e) {
			e.printStackTrace();
			
		}
		return "El correo no pudo ser enviado!";

	}

}
